import { outLogin, updatePass } from '@/services/common';
import { DownOutlined } from '@ant-design/icons';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Dropdown, Form, message } from 'antd';
import Cookies from 'js-cookie';
import { stringify } from 'querystring';
import { useState } from 'react';
const logo = '/images/logo.png';
const screen = '/images/screen.png';

const Header = () => {
  const [form] = Form.useForm<any>();
  const [resetPasswordsFlag, setResetPasswordsFlag] = useState<boolean>(false);
  const useInfo: any = window.sessionStorage.getItem('userInfo') || '{}';
  const handleOutLogin = async () => {
    const res = await outLogin();
    if (res?.code === 200) {
      // 遍历所有 cookie 并删除
      const cookies = Cookies.get();
      Object.keys(cookies).forEach((cookieName) => {
        Cookies.remove(cookieName);
      });
      window.localStorage.clear();
      window.sessionStorage.clear();
      const { search, pathname } = window.location;
      const urlParams = new URL(window.location.href).searchParams;
      /** 此方法会跳转到 redirect 参数所在的位置 */
      const redirect = urlParams.get('redirect');
      if (window.location.pathname !== '/login' && !redirect) {
        history.replace({
          pathname: '/login',
          search: stringify({
            redirect: pathname + search,
          }),
        });
      }
    }
  };
  const handleResetPasswords = async (value: any) => {
    if (value?.newPassWord !== value?.newPassWordAgain) {
      message.error('两次密码不一致');
      return false;
    } else {
      console.log({
        newPassWord: value.newPassWord,
        oldPassWord: value.oldPassWord,
        userId: JSON.parse(useInfo)?.userId,
      });
      try {
        const res = await updatePass({
          newPassWord: value.newPassWord,
          oldPassWord: value.oldPassWord,
          userId: JSON.parse(useInfo)?.userId,
        });
        if (res?.code === 200) {
          message.success('修改成功');
          setResetPasswordsFlag(false);
          return true;
        }
      } catch (error) {
        return false;
      }
    }
  };
  const userInfo = JSON.parse(
    window.sessionStorage.getItem('userInfo') || '{}',
  );

  return (
    <div className="header-layout-wrapper">
      <div className="header-left">
        <img src={logo} alt="" />
        <span>中央监护系统</span>
      </div>
      <div className="header-right">
        <img
          src={screen}
          alt=""
          className="screen-box"
          onClick={() => {
            window.open(`/dashboard`);
          }}
        />
        <Dropdown
          menu={{
            items: [
              {
                label: '退出登录',
                key: 'outLogin',
                onClick: () => handleOutLogin(),
              },
              {
                label: '重置密码',
                key: 'resetPasswords',
                onClick: () => setResetPasswordsFlag(true),
              },
            ],
          }}
          placement="bottomRight"
          arrow
        >
          <div className="username-wrapper">
            <span>{userInfo?.userName}</span>
            <DownOutlined />
          </div>
        </Dropdown>
      </div>
      {/* 修改密码 */}
      <ModalForm
        title="修改密码"
        form={form}
        autoFocusFirstInput
        width={500}
        modalProps={{
          destroyOnHidden: true,
          onCancel: () => setResetPasswordsFlag(false),
        }}
        open={resetPasswordsFlag}
        submitTimeout={2000}
        onFinish={async (value) => handleResetPasswords(value)}
      >
        <ProFormText
          name="oldPassWord"
          label="旧密码"
          placeholder="请输入旧密码"
          rules={[
            {
              required: true,
              message: '请输入旧密码',
            },
          ]}
        />
        <ProFormText
          name="newPassWord"
          label="新密码"
          placeholder="请输入新密码"
          rules={[
            {
              required: true,
              message: '请输入新密码',
            },
          ]}
        />
        <ProFormText
          name="newPassWordAgain"
          label="确认密码"
          placeholder="请输入确认密码"
          rules={[
            {
              required: true,
              message: '请输入确认密码',
            },
          ]}
        />
      </ModalForm>
    </div>
  );
};

export default Header;
